package fr.obsmip.sedoo.server.service;

import java.io.BufferedReader;
import java.io.InputStreamReader;
import java.net.URL;

import javax.net.ssl.HttpsURLConnection;

import org.json.simple.JSONObject;
import org.json.simple.parser.JSONParser;

import com.google.gwt.user.server.rpc.RemoteServiceServlet;

import fr.obsmip.sedoo.client.service.GoogleService;
import fr.obsmip.sedoo.core.RBVApplication;
import fr.obsmip.sedoo.core.dao.UserDAO;
import fr.obsmip.sedoo.core.domain.RBVUser;
import fr.obsmip.sedoo.server.service.dtotool.UserDTOTools;
import fr.obsmip.sedoo.shared.domain.RBVUserDTO;
import fr.sedoo.commons.client.util.ServiceException;

public class GoogleServiceImpl extends RemoteServiceServlet implements
GoogleService {

	private static final String GOOGLE_OAUTH_URL = "https://www.googleapis.com/oauth2/v1/userinfo?alt=json&access_token=";
	private static UserDAO dao = null;
	private final static String NAME_ATTRIBUTE="name";
	private final static String EMAIL_ATTRIBUTE="email";

	private void initDao() {

		if (dao == null)
		{
			dao = RBVApplication.getInstance().getUserDAO();
		}
	}

	@Override
	public RBVUserDTO getUserFromToken(String token) throws ServiceException {
		initDao();
		String urlString = GOOGLE_OAUTH_URL + token;
		RBVUser user = null;
		try
		{
		URL url = new URL(urlString);
		HttpsURLConnection conn = (HttpsURLConnection) url.openConnection();
		conn.setRequestMethod("GET");
		conn.setRequestProperty("Accept", "application/json");

		if (conn.getResponseCode() != 200) {
			throw new RuntimeException("Failed : HTTP error code : "
					+ conn.getResponseCode());
		}
		else
		{
			BufferedReader br = new BufferedReader(new InputStreamReader((conn.getInputStream())));
 			String output="";
 			String line ="";
				while ((line = br.readLine()) != null) {
					output = output+line;
				}
				conn.disconnect();
			
				JSONParser parser = new JSONParser();
				JSONObject jsonObject =  (JSONObject) parser.parse(output);
				String email  = (String) jsonObject.get(EMAIL_ATTRIBUTE);
				String name = (String) jsonObject.get(NAME_ATTRIBUTE);
				user = dao.getExternallyAuthenticatedUser(email);
				user.setName(name);
			}
		}
	catch (Exception e)
			{
				throw new ServiceException(e);
			}

		return UserDTOTools.toDTO(user);
	}


}

